package com.example.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    public static Logger logger= LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    private CaptchaProperties cp;

    //1分钟
    private static long VALID_TIME_OUT=60*1000;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session,HttpServletResponse response){
        //生成验证码,定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(),cp.getHeight());
        //打印验证码
        String code=lineCaptcha.getCode();
        System.out.println("System生成验证码："+code);
        logger.info("Logger生成验证码："+code);
        //存储session
        session.setAttribute(cp.getSession().getKey(),code);
        session.setAttribute(cp.getSession().getDate(),new Date());
        System.out.println(lineCaptcha.getCode());
        try {
            //把验证码写到浏览器
            lineCaptcha.write(response.getOutputStream());
            //设置contenttype，类型设置为图片
            response.setContentType("image/jepg");
            //设置编码
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma","No-cache");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session){
        System.out.println("输入的验证码："+captcha);
        //判空
        if(!StringUtils.hasLength(captcha)){
            return false;
        }

        String code= (String) session.getAttribute(cp.getSession().getKey());
        Date date = (Date)session.getAttribute(cp.getSession().getDate());
        //每秒是一千毫秒
        long time=60*1000;
        //如果日期为空或者超时
        if(date==null||System.currentTimeMillis()-date.getTime()>VALID_TIME_OUT){
            return false;
        }
        //不区分大小写
        return captcha.equalsIgnoreCase(code);
        //校验captcha是否正确


    }
}









